package com.qiaoba.module.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.qiaoba.module.system.entity.SysRoleMenu;
import com.qiaoba.module.system.mapper.SysRoleMenuMapper;
import com.qiaoba.module.system.service.SysRoleMenuService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 角色菜单关联 服务层实现
 *
 * @author ailanyin
 * @date 2023-09-10 14:26:28
 */
@Service
@RequiredArgsConstructor
public class SysRoleMenuServiceImpl implements SysRoleMenuService {

    private final SysRoleMenuMapper sysRoleMenuMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRoleMenu(String roleId, Set<String> menuIds) {
        // 删除之前的绑定
        QueryWrapper<SysRoleMenu> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(SysRoleMenu::getRoleId, roleId);
        sysRoleMenuMapper.delete(wrapper);
        // 重新绑定
        if (CollUtil.isNotEmpty(menuIds)) {
            List<SysRoleMenu> list = new ArrayList<>();
            for (String menuId : menuIds) {
                list.add(new SysRoleMenu(roleId, menuId));
            }
            // 批量新增
            Db.saveBatch(list);
        }
    }

    @Override
    public void deleteByRoleIds(List<String> ids) {
        sysRoleMenuMapper.deleteByRoleIds(ids);
    }
}
